package com.zhs.gccs.activity;

import static com.baidu.mapapi.BMapManager.getContext;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.annimon.stream.Optional;
import com.annimon.stream.Stream;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.zhs.gccs.R;
import com.zhs.gccs.activity.gccs.AdminGccsTaskActivity;
import com.zhs.gccs.activity.gccs.GccsUserTaskListActivity;
import com.zhs.gccs.base.BaseActivity;
import com.zhs.gccs.http.Api;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.model.DeviceInfo;
import com.zhs.gccs.model.DeviceRegisteBean;
import com.zhs.gccs.model.LoginBean;
import com.zhs.gccs.model.LoginSuccessBean;
import com.zhs.gccs.model.PhoneVerifyCodeBean;
import com.zhs.gccs.model.SysRole;
import com.zhs.gccs.model.SysUser;
import com.zhs.gccs.utils.DialogUtils;
import com.zhs.gccs.utils.GsonImpl;
import com.zhs.gccs.utils.NetWorkUtils;
import com.zhs.gccs.utils.OnNoDoubleClickListener;
import com.zhs.gccs.utils.PermissionListener;
import com.zhs.gccs.utils.RegexUtil;
import com.zhs.gccs.utils.ScreenUtils;
import com.zhs.gccs.utils.SharedPrefHelper;
import com.zhs.gccs.utils.SoftKeyboardUtils;
import com.zhs.gccs.utils.ToastUtils;
import com.zhs.gccs.utils.Utils;
import com.zhs.gccs.widget.CountDownTimerUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

public class LoginActivity extends BaseActivity {
    @BindView(R.id.ll_root)
    RelativeLayout llRoot;
    @BindView(R.id.login_username_et)
    EditText login_username_et;//登录账户
    @BindView(R.id.login_password_et)
    EditText login_password_et;//密码
    @BindView(R.id.v_del)
    View v_del;//输入删除
    @BindView(R.id.tv_get_code)
    TextView tv_get_code;//获取验证码
    //登录
    @BindView(R.id.ll_submit)
    LinearLayout ll_submit;//登录按钮
    ////////////////////////////////
    private Context mContext;

    public static void start(Context context) {
        context.startActivity(new Intent(context, LoginActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ImmersionBar.with(this).transparentBar().statusBarDarkFont(false).init();
        ButterKnife.bind(this);
        initView();
        mContext = this;
        initPermission();
    }

    void initPermission() {
        requestPermission(mContext, new PermissionListener() {
                    @Override
                    public void onSucceed() {
                        File file = new File(Utils.getMainPath(context));
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        initData();
                    }
                    @Override
                    public void onFailed() {
                        initPermission();
                    }
                }, PermissionConstants.STORAGE, PermissionConstants.CAMERA,
                PermissionConstants.MICROPHONE);
    }
    private void initData() {
        if (!TextUtils.isEmpty(SharedPrefHelper.getInstance().getLoginAccount())) {
            login_username_et.setText(SharedPrefHelper.getInstance().getLoginAccount());
            login_username_et.setSelection(login_username_et.getText().length());
        }
    }

    void initView() {
        tv_get_code.setVisibility(View.VISIBLE);
        login_username_et.setHint("请输入手机号");
        login_password_et.setInputType(InputType.TYPE_CLASS_PHONE);
        login_password_et.setHint("请输入验证码");
        v_del.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                login_username_et.setText("");
                login_password_et.setText("");
                SharedPrefHelper.getInstance().setLoginAccount("");
                v_del.setVisibility(View.INVISIBLE);
            }
        });
        tv_get_code.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (!login_username_et.getText().toString().isEmpty()) {
                    if (!RegexUtil.isMobileNO(login_username_et.getText().toString())) {
                        Toast.makeText(getContext(), "不是正确的手机号码", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    getPhoneVerifyCode(login_username_et.getText().toString());
                } else {
                    ToastUtils.toast("用户名不能为空");
                }
            }
        });

        login_username_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入前的监听
                if (!TextUtils.isEmpty(s)) {
                    v_del.setVisibility(View.VISIBLE);
                } else {
                    v_del.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        ll_submit.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                SoftKeyboardUtils.hideSoftInput(LoginActivity.this);
                if (!login_username_et.getText().toString().isEmpty()) {
                    //线上版本用手机号登录
                    if (!RegexUtil.isMobileNO(login_username_et.getText().toString())) {
                        Toast.makeText(getContext(), "不是正确的手机号码", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    ToastUtils.toast("用户名不能为空");
                    return;
                }
                if (!login_password_et.getText().toString().isEmpty()) {
                    if (login_password_et.getText().toString().length() < 4
                            && login_password_et.getText().toString().length() > 8) {
                        Toast.makeText(getContext(), "验证码位数错误", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    ToastUtils.toast("验证码不能为空");
                    return;
                }
                showDialog();
                loginOnline();
            }
        });
    }
    //////////////////////////////////////////////////
    public void getPhoneVerifyCode(String phone) {
        CountDownTimerUtils mCountDownTimerUtils = new
                CountDownTimerUtils(this, tv_get_code, 60000, 1000); //倒计时1分钟
        mCountDownTimerUtils.start();
        ToastUtils.toast("正在获取验证码");
        toSubscribeSingleOb(Api.getDefault().getVerifyCode(phone),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        PhoneVerifyCodeBean bean = GsonImpl.get().toObject(result, PhoneVerifyCodeBean.class);
                        if (bean.getCode() != 200) {
                            ToastUtils.toast("获取验证码失败");
                            return;
                        }
                    }
                    @Override
                    protected void _onError(String result) {
                        ToastUtils.toast("获取验证码失败");
                    }
                });
    }

    public void loginOnline() {
        if(!NetWorkUtils.isNetworkAvailable(context)){
            ToastUtils.toast("您的设备没有网络");
            return;
        }
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setDevice("android");
        deviceInfo.setModel(DeviceUtils.getModel());
        deviceInfo.setDeviceId(DeviceUtils.getAndroidID());
        deviceInfo.setUniqueDeviceId(DeviceUtils.getUniqueDeviceId());
        deviceInfo.setManufacturer(DeviceUtils.getManufacturer());
        deviceInfo.setSdkVersionCode(DeviceUtils.getSDKVersionCode());
        deviceInfo.setSdkVersionName(DeviceUtils.getSDKVersionName());
        deviceInfo.setAppName(AppUtils.getAppName());
        deviceInfo.setAppVersionCode(AppUtils.getAppVersionCode());
        deviceInfo.setAppVersionName(AppUtils.getAppVersionName());
        deviceInfo.setSha1(ScreenUtils.sHA1(context));
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("phoneNumber", login_username_et.getText().toString());
        hashMap.put("verificationCode", login_password_et.getText().toString());
        hashMap.put("deviceInfo", deviceInfo);
        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault().hcAppLogin2(requestBody),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        LoginSuccessBean bean = GsonImpl.get().toObject(result, LoginSuccessBean.class);
                        if (bean.getCode() == 2000) {//设备未注册
                            dismissDialog();
                            DialogUtils.showPromote2(context, "设备未注册，是否注册该设备?", new DialogUtils.OnCancelListener() {
                                @Override
                                public void onCanceled() {

                                }
                            }, new DialogUtils.OnConfirmListener() {
                                @Override
                                public void onConfirmed() {
                                    confirmBindDevice(login_username_et.getText().toString(), deviceInfo);
                                }
                            });
                            return;
                        } else if (bean.getCode() == 2001) {//设备还没通过审核
                            dismissDialog();
                            ToastUtils.toast(bean.getMsg());
                            return;
                        }
                        if (bean.getCode() != 200) {
                            dismissDialog();
                            ToastUtils.toast("登录失败: " + bean.getMsg());
                            return;
                        }
                        //登录成功
                        String token = bean.getData();
                        SharedPrefHelper.getInstance().setToken(token);
                        String username = login_username_et.getText().toString();
                        SharedPrefHelper.getInstance().setLoginAccount(username);
                        SharedPrefHelper.getInstance().setLastLoginTime(System.currentTimeMillis());
                        //注册设备
//                        Intent intent = new Intent(context, MainActivity.class);
                        /*Intent intent = new Intent(context, AdminGccsTaskActivity.class);
                        startActivity(intent);
                        finish();*/
                        getLoginUserInfo();
                        dismissDialog();
                    }

                    @Override
                    protected void _onError(String result) {
                        ToastUtils.toast("登录失败: 请检查您的网络");
                        dismissDialog();
                    }
                });
    }

    //获取用户信息及权限
    private void getLoginUserInfo() {
        //getInfo
        toSubscribeSingleOb(Api.getDefault().getUserInfo(),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        LoginBean loginBean = JSON.parseObject(result, LoginBean.class);
                        if (loginBean == null
                                ||loginBean.getCode() != 200
                                || loginBean.getData() == null) {
                            ToastUtils.toast("获取用户信息失败，请重新登录!");
                            return;
                        }
                        LoginBean.LoginInfo data = loginBean.getData();
                        List<String> roles = data.getRoles();
                        if(roles==null||roles.size()==0){
                            DialogUtils.showPromote1(context, "您暂未分配权限，请联系管理员", new DialogUtils.OnConfirmListener() {
                                @Override
                                public void onConfirmed() {
                                }
                            });
                            return;
                        }
                        List<String> permissions = data.getPermissions();
                        SharedPrefHelper.getInstance().setUserRoles(roles);
                        SysUser sysUser = data.getUser();
                        SharedPrefHelper.getInstance().
                                setUserNickName(sysUser.getNickName());
                        SharedPrefHelper.getInstance().
                                setUserAccount(sysUser.getUserName());
                        SharedPrefHelper.getInstance().
                                setUserOrgName(sysUser.getDept() != null ? sysUser.getDept().getDeptName() : "");
                        SharedPrefHelper.getInstance().
                                setUserXzq(sysUser.getXzq());
//                        Optional<String> gccscjrRole = Stream.of(roles).
//                                filter(i -> SysRole.role_gccs_admin.equals(i)).findFirst();
//                        if(gccscjrRole.isPresent()){
//                            AdminGccsTaskActivity.start(LoginActivity.this);
//                        }else {
//                            GccsUserTaskListActivity.start(LoginActivity.this);
//                        }
                        DrawerMainActivity.start(LoginActivity.this);
                    }
                    @Override
                    protected void _onError(String result) {
                        ToastUtils.toast("获取用户信息失败，请重新登录!");
                    }
                });
    }

    //设备绑定
    private void confirmBindDevice(String phone, DeviceInfo deviceInfo) {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("phoneNumber", phone);
        hashMap.put("deviceInfo", deviceInfo);
        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault().deviceBind(requestBody),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        DeviceRegisteBean bean = JSON.parseObject(result, DeviceRegisteBean.class);
                        if (bean.getCode() == 2000) {
                            dismissDialog();
                            ToastUtils.toast(bean.getMsg());
                            return;
                        }
                        if (bean.getCode() != 200) {
                            dismissDialog();
                            ToastUtils.toast("注册设备失败: " + bean.getMsg());
                            return;
                        }
                        dismissDialog();
                        ToastUtils.toast("注册设备成功，请等待管理员审核");
                    }

                    @Override
                    protected void _onError(String result) {
                        ToastUtils.toast("注册设备失败");
                        dismissDialog();
                    }
                });
    }
}
